//
//  HSettingViewController.m
//  NursingManages
//
//  Created by HuangZhen on 2017/5/26.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "HSettingViewController.h"
#import "TableEmployee.h"

#import "HMyQrCodeViewController.h"
#import "HDowloadDataViewController.h"
#import "HSysToolsViewController.h"
#import "HUploadDataViewController.h"
#import "AppDelegate.h"
#import "HCompanyViewController.h"
#import "ImagePickerCropViewController.h"
#import "HttpDownload.h"
#import "DIPubQuality.h"

@interface HSettingViewController ()

@property NSInteger kContactHeadviewHeight;
@property UIImagePickerController* picker;
@property (nonatomic,strong)NSDictionary *DataSourceIcon;

@property NSTimer* myTimer;
@property (nonatomic ,assign)int timeout;
@end

@implementation HSettingViewController



-(instancetype)init{
    
    if (self) {
        
        [self setUpView];

    }
    
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    [self.myTableView setTableHeaderView: self.GetiPhoneSytleHeadView];
    [self.view addSubview:self.myTableView];
    self.view.backgroundColor = RGB(236,236,245);
}



- (void)setUpView
{
    self.theEmployee = UserDefault.getUserInfo;
    
    NSLog(@"iPhone 持久化地址：%@", [self DocumentsDirectory]);
    
    self.kContactHeadviewHeight = 100;
    
    self.DataSource = [[NSDictionary alloc ]init];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    NSArray *arr1 = [[NSArray alloc]initWithObjects:@"我的条码", nil];
    NSArray *arr2 = [[NSArray alloc]initWithObjects:@"上传数据", @"下载数据",@"更新参数", nil];
    NSArray *arr3 = [[NSArray alloc]initWithObjects:@"系统工具",F(@"版本号v%@",appVersion), @"关于图特",nil];
    
    
    NSArray *arr1_icon = [[NSArray alloc]initWithObjects:@"条码", nil];
    NSArray *arr2_icon = [[NSArray alloc]initWithObjects:@"上传", @"下载",@"参数", nil];
    NSArray *arr3_icon = [[NSArray alloc]initWithObjects:@"工具",@"版本",@"关于-点击", nil];
    
    self.DataSource = [[NSDictionary alloc]initWithObjectsAndKeys:
                       arr1, @"A", arr2 , @"B", arr3, @"C" , nil ];
    
    self.DataSourceIcon = [[NSDictionary alloc]initWithObjectsAndKeys:
                           arr1_icon, @"A", arr2_icon , @"B", arr3_icon, @"C" , nil ];

}


- (UITableView *)myTableView{
    if (!_myTableView ) {
        _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, NavBarHeight, ScreenWidth, ScreenHeight)];
        _myTableView.dataSource = self;
        _myTableView.delegate = self;
        _myTableView.tableFooterView = [self GetFootView];
        _myTableView.backgroundColor = RGB(236,236,245);
    }
    return _myTableView;
}

#pragma mark UITableView 头部姓名和拨号，仿iPhone联系人明细界面

-(void)CallBack:(NSObject *)object{
    
    if ([object isKindOfClass:[UIImage class]] ){
        
        UIImage *image = (UIImage*)object;
        NSString *filePath = [[super DocumentsDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:@"USERHEAD_BY_USERID_%@.png",UserDefault.getUserInfo.USER_ID]];   // 保存
        [UIImagePNGRepresentation(image)writeToFile: filePath atomically:YES];
        
        UIView *tableHeadview = self.myTableView.tableHeaderView;
        UIImageView *headerimagev = tableHeadview.subviews[0].subviews[0];
        [headerimagev setImage:image];
        
        [self.picker dismissViewControllerAnimated:YES completion:nil];
    }
    
}

-(IBAction)changeHeadImage:(id)sender{
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    self.picker = picker;
    [self.view.window.rootViewController presentViewController:picker animated:YES completion:nil];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *image = [info  objectForKey:UIImagePickerControllerOriginalImage];
    ImagePickerCropViewController *vc = [[ImagePickerCropViewController alloc] init];
    vc.originImage = image;
    vc.delegate = self;
    
    [picker pushViewController:vc animated:true];
    
    /*
    NSString *filePath = [[super DocumentsDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:@"USERHEAD_BY_USERID_%@.png",UserDefault.getUserInfo.USER_ID]];   // 保存
    [UIImagePNGRepresentation(image)writeToFile: filePath atomically:YES];
    
    UIView *tableHeadview = self.myTableView.tableHeaderView;
    UIImageView *headerimagev = tableHeadview.subviews[0].subviews[0];
    [headerimagev setImage:image];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
     */
}

-(UIView *) GetHeadImageView{
    
    
    NSString *filePath = [[super DocumentsDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:@"USERHEAD_BY_USERID_%@.png",UserDefault.getUserInfo.USER_ID]];
    BOOL hasHeaderImage = [super fileExistsAtPath:filePath];
    
    
    NSInteger picHeight = 60;
    NSInteger picWidth = picHeight;
    
    UIView*view = [[UIControl alloc] initWithFrame:CGRectMake(20, 20, picWidth, picHeight)];
    view.backgroundColor = [UIColor clearColor];
    [(UIControl *)view addTarget:self action:@selector(changeHeadImage:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height)];
    imageV.layer.cornerRadius = picWidth / 2;
    imageV.layer.masksToBounds = YES;
    if(hasHeaderImage){
        
        NSData *imageData = [NSData dataWithContentsOfFile:filePath];
        
        [imageV setImage:[UIImage imageWithData:imageData]];
        
    }else{
        [imageV setImage:[UIImage imageNamed:@"护士"]];
    }
    [view addSubview:imageV];
    
    return view;
}


-(UIView *) GetiPhoneSytleHeadView{
    
    UIView *headview = [[UIView alloc]initWithFrame:CGRectMake(0, NavBarHeight, 300, _kContactHeadviewHeight)];
    headview.backgroundColor = UIColor.whiteColor;
    UIView *headPic = [self GetHeadImageView];
    
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(headPic.right + 15, headPic.top * 1.3, ScreenWidth - headPic.right - 10, 30)];
    nameLabel.text = [NSString stringWithFormat:@"%@(%@)",self.theEmployee.USER_NAME,self.theEmployee.USER_CODE];
  
    UILabel *hospitalLabel = [[UILabel alloc]initWithFrame:CGRectMake(headPic.right + 15, headPic.bottom - 30, ScreenWidth - headPic.right - 10, 30)];
    hospitalLabel.text =  self.theEmployee.HOSPITAL_NAME;
    hospitalLabel.textColor = [UIColor grayColor];
    
    [headview addSubview:headPic];
    [headview addSubview:nameLabel];
    [headview addSubview:hospitalLabel];
    return headview;
}


#pragma mark 退出登录

-(void)LogOut:(id)sender
{
    [self confirm:@"您确认要退出吗？"
    callbackYesFn:^(void){
        
        [UserDefault clearUserData];
        AppDelegate *app = (AppDelegate *)[[UIApplication  sharedApplication] delegate];
        [app rootViewToTabBar];
    }
    callbackNoFn:^(void){
        
    }];
}
-(UIView*)GetFootView{
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 42)];
    footView.backgroundColor = RGB(249, 249, 249);
    
    UIButton *logOutButton = [UIButton buttonWithType:UIButtonTypeCustom];
    logOutButton.frame = CGRectMake(0, 0, ScreenWidth, 42);
    [logOutButton setTitle:@"退出登录" forState:UIControlStateNormal];
    [logOutButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    logOutButton.backgroundColor = [UIColor whiteColor];
    [logOutButton addTarget:self action:@selector(LogOut:) forControlEvents:UIControlEventTouchUpInside];
    
    [footView addSubview:logOutButton];
    
    return footView;
}

-(NSArray*)GetArrBySection:(NSInteger) section{
    NSArray *array = self.DataSource[self.DataSource.allKeys[section]];
    return array;
}

#pragma mark UITableView 委托


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if(section == self.DataSource.allKeys.count - 1){
        return 20;
    }
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [[UIView alloc]init];
    footView.backgroundColor = RGB(236,236,245);
    return footView;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headView = [[UIView alloc]init];
    headView.backgroundColor = RGB(236,236,245);
    return headView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.DataSource.allKeys.count;     
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *array = [self GetArrBySection:section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cell";

    UITableViewCell *cell = [self.myTableView dequeueReusableCellWithIdentifier:cellID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    
//    UIImageView *rightImage = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth - 15, 10, 8, 18)];
//    rightImage.image = [UIImage imageNamed:@"icon_right"];
    NSString *key = self.DataSource.allKeys[indexPath.section];
    NSArray *arr = self.DataSource[key];
    NSArray *arr_icon = self.DataSourceIcon[key];
    cell.textLabel.text = arr[indexPath.row];
    if (![[arr[indexPath.row] substringToIndex:3] isEqualToString:@"版本号"]) {

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    [cell.imageView setImage:[UIImage imageNamed:arr_icon[indexPath.row]]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSArray *array = [self GetArrBySection:indexPath.section];
    
    NSString *title = array[indexPath.row];
    
    if([title isEqualToString:@"我的条码"]){
        HMyQrCodeViewController *view = [[HMyQrCodeViewController alloc]init];
        view.hidesBottomBarWhenPushed = YES;
        view.title = title;
        [self.navigationController pushViewController:view animated:YES];
    }
    else if([title isEqualToString:@"下载数据"]){

        HDowloadDataViewController *down = [[HDowloadDataViewController alloc]init];
        down.hidesBottomBarWhenPushed = YES;
        down.title = title;
        [self.navigationController pushViewController:down animated:YES];
    }
    else if ([array[indexPath.row] isEqualToString:@"上传数据"]){
        
        HUploadDataViewController *view = [[HUploadDataViewController alloc]init];
        view.hidesBottomBarWhenPushed = YES;
        view.title = title;
        [self.navigationController pushViewController:view animated:YES];

    }
    else if([title isEqualToString:@"系统工具"]){
        
        HSysToolsViewController *view = [[HSysToolsViewController alloc]init];
        view.hidesBottomBarWhenPushed = YES;
        view.title = title;
        [self.navigationController pushViewController:view animated:YES];
    }
    else if ([title isEqualToString:@"关于图特"]){
        HCompanyViewController *HCompanyVC =[[HCompanyViewController alloc]init];
        HCompanyVC.hidesBottomBarWhenPushed = YES;
        HCompanyVC.title = @"关于图特";
        [self.navigationController pushViewController:HCompanyVC  animated:YES];
    }
    
    else if ([title isEqualToString:@"更新参数"]) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否更新系统参数?"
                                                        message:nil
                                                       delegate:nil
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"确定", nil];
        [alert show];
        alert.tag = 200;
        alert.delegate = self;

        
    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 200) {
        switch (buttonIndex) {
            case 0:{
                return;
            }
                break;
            case 1:{
                
                [HCommon popupMessage:@"正在下载，请稍候"];
                
                dispatch_queue_t conCurrentQueue = dispatch_queue_create("com.thothinfo.conCurrentQueue", DISPATCH_QUEUE_CONCURRENT);
                
                dispatch_async(conCurrentQueue, ^{
                    [[[DIPubQuality alloc]init]startDownloadParam:^(){
                        
                    }];
                });
                
                self.timeout = 60 * 3;
                self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerCalled:) userInfo:@1 repeats:YES];
                

            }
                break;
            default:
                break;
        }
    }
}


-(void)timerCalled:(NSTimer*) timer{
    self.timeout --;
//    if(self.httpDownload.isDownloadOver == YES){
        [HCommon popupSuccessMessage:@"更新完成"];
        [self.myTimer invalidate];
        self.myTimer = nil;
//    }
    if (self.timeout == 0) {
        [HCommon dismissAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
